import { cloneDeep } from 'lodash';

export const EVENT_TYPE = {
  AUTO_ROLL_CALL: 'auto_roll_call',
  BEGIN_AUTO_ROLL_CALL: 'begin_auto_roll_call',
  ADD_DOCTOR_RECORD: 'addDoctorRecord',
  RE_ADD_DOCTOR_RECORD: 're_addDoctorRecord',
  CONSULTATION: 'consultation',
  RE_CONSULTATION: 're_consultation',
  MEDICINE_CALL: 'medicineCall',
  BEGIN_MEDICINE_CALL: 'begin_medicineCall',
  EMERGEN_REPORT: 'emergen_report',
  INPSTORE_EMERGEN_REPORT: 'inspector_emergen_report',
  PC_EMERGEN_REPORT: 'pc_emergen_report',
  RE_PC_EMERGEN_REPORT: 're_pc_emergen_report',
  ALARAM: 'alarm',
  ALARAM_CONFIRM: 'alarm_confirm',
  PC_ALARAM: 'pc_alarm',
  IN_REGIS: 'in_regis',
  OUT_REGIS: 'out_regis',
  BEGIN_IN_REGIS: 'begin_in_regis',
  BEGIN_OUT_REGIS: 'begin_out_regis',
  SHEN_HE_TONG_GUO: 'shenhetonguo',
  BEGIN_SHEN_HE_TONG_GUO: 'begin_shenhetonguo',
  ADD_TASK: 'add_task',
  BEGIN_ADD_TASK: 'begin_add_task',
};

export const CACHE_KEY = {
  DOCTOR_RECORD: 'doctor_record',
  PRISION_LIST: 'prison_list',
  MEETING_LIST: 'meeting_list',
  TASK_LIST: 'task_list',
};

export const DATA_FORMAT = 'YYYY-MM-DD hh:mm:ss';

export const setCache = (key: string, data: any, force = false) => {
  if (!localStorage.getItem(key)) {
    localStorage.setItem(key, JSON.stringify(data));
  } else {
    if (force) {
      localStorage.setItem(key, JSON.stringify(data));
    }
  }
};

export const setCacheByKey = (cacheKey: string, findFunc: any, vals: any) => {
  const data = cloneDeep(getCache(cacheKey));
  const index = data.findIndex(findFunc);
  data[index] = { ...data[index], ...vals };
  setCache(cacheKey, data, true);
  return data;
};

export const getCache = (key: string) => {
  let str = localStorage.getItem(key);
  if (str) str = JSON.parse(str);
  return str;
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const onEvent = (eventType: any, callback: (data: any) => any) => {
  const bc = new BroadcastChannel('inspector_prison');
  if (bc)
    bc.onmessage = function (ev) {
      console.log('收到消息啦', ev.data);
      const { type } = ev.data;
      if (type === eventType) {
        callback(ev.data.data);
      }
    };
};

export const emitEvent = (type: any, data: any) => {
  const bc = new BroadcastChannel('inspector_prison');
  bc.postMessage({
    type,
    data,
  });
};

export const getThemeCache = () => {
  const theme = localStorage.getItem('theme');
  return theme;
};
